package com.ruoyi.hire.controller.company;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.constant.CompanyConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.hire.domain.HireCompany;
import com.ruoyi.hire.domain.vo.CompanyRegisterCaptchaCodeVo;
import com.ruoyi.hire.domain.vo.CompanyRegisterVo;
import com.ruoyi.hire.domain.vo.ValidateSmsResultVo;
import com.ruoyi.hire.service.IHireCompanyLoginService;
import com.ruoyi.hire.service.IHireCompanyService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController("CompanyRegisterController")
public class RegisterController {


    @Resource
    private IHireCompanyService hireCompanyService;


    @Resource
    private IHireCompanyLoginService hireCompanyLoginService;


    @Resource
    private RedisCache redisCache;

    /**
     * 用人单位注册时的短信验证码校验
     *
     * @param vo
     * @return
     */
    @PostMapping("/site/hire/company/register")
    public AjaxResult register(@RequestBody CompanyRegisterVo vo) {
        if (!vo.getPassword().equals(vo.getCheckPassword())) {
            return AjaxResult.error("两次密码输入不一致");
        }
        //校验短信验证码
        ValidateSmsResultVo validateSmsResultVo = hireCompanyLoginService.validateSms(vo.getPhoneNumber(), vo.getSmsCode());
        //如果短信验证码校验失败
        if (!validateSmsResultVo.getResult()) {
            return AjaxResult.error(validateSmsResultVo.getMessage());
        }
        //判断两次密码输入是否一致
        if (!vo.getPassword().equals(vo.getCheckPassword())) {
            return AjaxResult.error("两次密码输入不一致");
        }
        //判断下，当前手机号是否已经注册
        Long count = hireCompanyService.selectHireCompanyByAccount(vo.getPhoneNumber());
        if (count > 0L) {
            return AjaxResult.error("当前手机号已注册，请直接登入");
        }
        Long id = hireCompanyService.register(vo);
        //注册成功后，清除短信验证码
        redisCache.deleteObject(CompanyConstants.COMPANY_REGISTER_SMS_CODE_KEY + vo.getPhoneNumber());
        if (ObjectUtil.isEmpty(id) || id == 0L) {
            return AjaxResult.error("注册失败，请和网站管理员联系");
        }
        StpUtil.login(id);
        // 第2步，获取 Token  相关参数
        String token = StpUtil.getTokenInfo().tokenValue;
        return AjaxResult.success(token);
    }

}
